class ProductsController < ApplicationController
  # GET /products
  # GET /products.xml
  layout "admin"
  before_filter :admin?,:except=>[:show,:search,:list,:result]
  before_filter :initialize_cart,:only=>[:list,:show,:search,:result]
  cache_sweeper :link_sweeper,:only=>[:create,:destroy,:update]
  def index
    #@products = Product.find(:all)
    #load_data params[:page]
    @products=Product.paginate_by_sql(create_sql(params[:p],params["product_name"].blank? ? nil : "p.name like '%#{params["product_name"]}%'"), :page =>params[:page], :per_page =>10)
    respond_to do |format|
      format.html
      format.js do render :update do |page|
          page.replace_html("pro_list",:partial=>"pro_items",:object=>@products)
        end
      end
      format.xml  { render :xml => @products }
    end
  end
  def list
    #load_data params[:page],20,nil,"click_count desc"
    @products=Product.paginate_by_sql(create_sql(params[:p],params[:procate_id].blank? || params[:procate_id]=="all" ? nil : "procate_id=#{params[:procate_id]}"), :page =>params[:page], :per_page =>30)
    @page_title="产品列表"
    @page_nav="><a href='/procates/all/products/list'>产品中心</a>>&nbsp;"
    @page_nav+= params[:procate_id]=="all" ? "所有产品" : Procate.find(params[:procate_id]).description
    respond_to do |format|
      format.html {render :layout=>"front_page"}
      format.xml  { render :xml => @products }
    end
  end

  def search
    @page_title="产品搜索"
    @page_nav="><a href='/procates/all/products/list'>产品中心</a>>"
    @page_nav+="产品搜索"
    respond_to do |format|
      format.html {render :layout=>"front_page"}
    end
  end
  def result
    @page_title="产品搜索结果"
    @page_nav="><a href='/procates/all/products/list'>产品中心</a>"
    @page_nav+=">&nbsp;搜索结果"
    pro_conditions=""
    unless params[:product_name].blank?
      pro_conditions+=" p.name like '%#{params[:product_name]}%' "
    end
    if !params[:scope1].blank? && !params[:scope2].blank?
      pro_conditions+=" and " unless pro_conditions.blank?
      pro_conditions+=" now_price > #{params[:scope1]} and  now_price < #{params[:scope2]}"
    elsif !params[:scope1].blank?
      pro_conditions+=" and " unless pro_conditions.blank?
      pro_conditions+=" now_price > #{params[:scope1]}"
    elsif !params[:scope2].blank?
      pro_conditions+=" and " unless pro_conditions.blank?
      pro_conditions+=" now_price < #{params[:scope2]}"
    end
    @products=Product.find_by_sql(create_sql(params[:product_attribute_values],pro_conditions))
    respond_to do |format|
      format.html {render :layout=>"front_page"}
    end
  end

  # GET /products/1
  # GET /products/1.xml
  def show
    @product = Product.find(params[:id])
    @page_title,@page_key=@product.name
    @page_des=@product.short_description
    @product.increment!("click_count", 1)

    @page_nav="><a href='/procates/all/products/list'>产品中心</a>"
    @page_nav+="><a href='#{list_procate_products_path(@product.procate_id)}'>#{@product.procate.description}</a>>&nbsp;"
    @page_nav+=@product.name
    respond_to do |format|
      format.html { render :layout=>"front_page"}
      format.xml  { render :xml => @product }
    end
  end

  # GET /products/new
  # GET /products/new.xml
  def new
    @product = params[:id].blank? ? Product.new : Product.find(params[:id])
    @pro_content=params[:id].blank? ? ProContent.new : @product.pro_content
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @product }
    end
  end

  # GET /products/1/edit
  def edit
    @product = Product.find(params[:id])
    @pro_content=@product.pro_content || ProContent.new
  end
  def copy
    @product=Product.find(params[:id])
    @product_copy=@product.clone
    @product_copy.created_at=@product_copy.updated_at=nil
    @product_copy.click_count=0
    @product_copy.pro_content=@product.pro_content.clone
    @product_copy.main_image=@product.main_image ? @product.main_image.clone : nil
    @product.pro_images.each do |image|
      @product_copy.pro_images<<image.clone
    end
    @product.product_attribute_values.each do |value|
      @product_copy.product_attribute_values<<value.clone
    end

    if(@product_copy.save)
      flash[:notice] = '拷贝成功！'
    else
      flash[:notice] = '拷贝失败!,请重新操作或与管理员联系！'
    end
    redirect_to(procate_products_path(0))

      
  end

  # POST /products
  # POST /products.xml
  def create
    @product = Product.new(params[:product])
    @product.main_image=ProImage.new(:image=>params[:img],:img_type_id=>1)
    @product.pro_content=ProContent.new(params[:pro_content])
    #params[:pro_values].each_value{|attr| @product.product_attribute_values.build(attr)}
    respond_to do |format|
      if @product.save
        flash[:notice] = 'Product was successfully created.'
        format.html { redirect_to(new_product_product_attribute_value_path(@product)) }
        #        format.js do
        #          load_data params[:page]
        #          render :update do |page|
        #            page.replace_html "pro_list", :partial=>"pro_items",:object=>@products
        #            page.replace_html "operate",""
        #          end
        #        end
        format.xml  { render :xml => @product, :status => :created, :location => @product }
      else
        format.html { render :action => "new" }
        format.js  { render :js => "alert('出错，请重新添加！');" }
        format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /products/1
  # PUT /products/1.xml
  def update
    @product = Product.find(params[:id])
    unless params[:img].blank?
      if @product.main_image       
        @product.main_image.update_attributes(:image=>params[:img])
      else
        @product.main_image=ProImage.new(:image=>params[:img],:img_type_id=>1)
      end
    end
   
    @product.pro_content ? @product.pro_content.update_attributes(params[:pro_content]):@product.pro_content=ProContent.new(params[:pro_content])
    respond_to do |format|
      if @product.update_attributes(params[:product])
        flash[:notice] = 'Product was successfully updated.'
       
        format.html { redirect_to(procate_products_path(0)) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /products/1
  # DELETE /products/1.xml
  def destroy
    @product = Product.find(params[:id])
    @product.destroy
    load_data(params[:page])
    respond_to do |format|     
      format.html { redirect_to(products_url) }
      format.js {render :partial=>"pro_items",:object=>@products}
      format.xml  { head :ok }
    end
  end
  private
  def load_data(page,page_size=10,search=nil,order=nil)
    @products = Product.paginate :per_page=>page_size,:page=>page || 1,:conditions=>search,:order=>order ? order:"created_at desc",:include=>[:main_image,:tuangou_pro]
  end
  def create_sql(attrs,pro_condition=nil)
    attrs.delete_if { |key,value| value.values[0].blank? || value.values[0]=="0" } if attrs #删除值为空及为0的对;
    sql="select p.*,p1.name img from products p left join pro_images p1 on (p.id=p1.product_id and p1.img_type_id=1) "
    if !attrs.nil? && !attrs.empty? #如果有健值对
      sql+="where p.id in (select a.* from"
      attrs.each do |key,value|
        col=if value.keys[0]=~/\d/#如果是点击品牌进来，通过get
          case value.keys[0]
          when "1","2"
            " where product_attribute_template_id=#{key} and value_int=#{value.values[0]}"
          when 3
            " where product_attribute_template_id=#{key} and value_str like '%#{value.values[0]}%'"
          when 4
            " where product_attribute_template_id=#{key} and value_bool=#{value.values[0]}"
          else
            nil
          end
        else #如果是通过post,并且值不为空
          if value.keys[0]=="value_str"
            "where product_attribute_template_id=#{key} and #{value.keys[0]} like '#{value.values[0]}'"
          else
            "where product_attribute_template_id=#{key} and #{value.keys[0]}=#{value.values[0]}"
          end
        end
        if attrs.keys.index(key)==0 #如果是第一个键值对，子表就不用进行联接，如果非第一个，则需要进行联接查询
          sql+="(select product_id from product_attribute_values #{col}) as a "
        else
          sql+=" inner join (select product_id from product_attribute_values  #{col}) as a#{key} on a#{key}.product_id=a.product_id"
        end
      end
      sql+=")"
    end
    unless pro_condition.blank? #产品表内字段的查询
      if !attrs.nil? && !attrs.empty?
        sql+=" and #{pro_condition} "
      else
        sql+=" where #{pro_condition} "
      end
    end
    sql+=" order by p.created_at desc"
  end
end